<template>
	<view class="container">
		<!-- 注册表单 -->
		<up-form labelPosition="left" :model="form" :rules="rules" ref="formRef">
			<!-- 账号输入框 -->
			<up-form-item label="账号" prop="userAccount" borderBottom label-width="150rpx">
				<up-input v-model="form.userAccount" border="none" placeholder="请输入账号"></up-input>
			</up-form-item>

			<!-- 密码输入框 -->
			<up-form-item label="密码" prop="userPassword" borderBottom label-width="150rpx">
				<up-input v-model="form.userPassword" border="none" placeholder="请输入密码" password></up-input>
			</up-form-item>

			<up-form-item label="确认密码" prop="checkPassword" borderBottom label-width="150rpx">
				<up-input v-model="form.checkPassword" border="none" placeholder="确认密码" password></up-input>
			</up-form-item>
		</up-form>

		<!-- 注册按钮 -->
		<up-button type="primary" text="注册" customStyle="margin-top: 50px" @click="submit" shape="circle"></up-button>

	</view>
</template>

<script setup lang="ts">
	import { ref } from "vue";
	import myAxios from "@/plugins/myAxios";

	// 表单数据
	const form = ref({
		userAccount: "",
		userPassword: "",
		checkPassword: ""
	});

	// 表单校验规则
	const rules = {
		userAccount: [
			{ required: true, message: "请输入账号", trigger: "blur" },
		],
		userPassword: [
			{
				required: true,
				message: "请输入密码",
				trigger: "blur",
			},
		],
		checkPassword:[{
				required: true,
				message: "请重新输入密码",
				trigger: "blur",
			},]
	};

	// 表单引用
	const formRef = ref();

	// 注册逻辑
	const submit = () => {
		formRef.value.validate(async (valid : boolean) => {
			if (valid) {
				// 表单校验通过后提交
				await onSubmit();
			} else {
				uni.showToast({
					title: "请检查表单输入",
					icon: "none",
					duration: 2000,
				});
			}
		});
	};

	const onSubmit = async () => {
		try {
			// 提交数据到后端
			const res = await myAxios.post("/user/register", {
				userAccount: form.value.userAccount,
				userPassword: form.value.userPassword,
				checkPassword: form.value.checkPassword
			});

			// 注册成功逻辑
			if (res.code === 0 && res.data) {
				const redirectUrl = getApp().globalData.redirectUrl || "/pages/index/index";
				uni.showToast({
					title: "注册成功",
					icon: "success",
					duration: 2000,
				});
				uni.reLaunch({
					url: redirectUrl,
				});
			} else {
				// 注册失败逻辑
				uni.showToast({
					title: "注册失败: " + res.description,
					icon: "none",
					duration: 2000,
				});
			}
		} catch (error) {
			// 异常处理
			console.error(error);
			uni.showToast({
				title: "注册异常，请稍后重试",
				icon: "none",
				duration: 2000,
			});
		}
	};
</script>

<style lang="scss">
	.container {
		padding: 15px;
	}
</style>